#include "iceberg.h"
#include <iostream>
#include <fstream>
#include <csignal>
#include <sys/types.h>

using namespace std;

bool waiting = true;
void WakeUp ( int signal );

int main ( int argc, char *argv[] )
{
	Iceberg iceberg;

	if ( argc != 8 )
        {
                cerr << "Decrypt: Ivalid arguments\n";
                exit ( 1 );
        }

	ifstream inputFile ( argv[1], ios::in );
	ofstream outputFile ( argv[2], ios::binary );
	int offset = atoi ( argv[3] );
	string hexKeyStr ( argv[4] );
	int lenght = atoi ( argv[5] );
	int previousPid = atoi ( argv[6] );
	int rounds = atoi ( argv[7] );

	signal ( SIGUSR1, WakeUp );
	kill ( getppid(), SIGUSR1 );

	while ( waiting ) {}

	/* ......... ... ........... ......... .. .......... */

	if ( previousPid != 0 )
	{
		kill ( previousPid, SIGUSR1 );
	}

	inputFile.seekg ( offset * 8, ios::beg );
	outputFile.seekp ( offset * 8, ios::beg );

	Message key ( 32, hexKeyStr, true );

	for ( int i = 0; i < lenght; i++ )
	{
		char buffer[8];

		inputFile.read (  buffer, 8 );
		string messageStr ( buffer );
		Message message ( 8, messageStr );
		Message decrypted( iceberg.Decrypt ( key, message, rounds ) );
		outputFile << decrypted;
	}

	outputFile.close();
}

void WakeUp ( int signal )
{
	if ( signal == SIGUSR1 )
	{
		waiting = false;
	}
}
